import { NextResponse } from 'next/server'
import { pool } from '../db'

export interface HotArticle {
  id?: number
  post_id: number
  title: string
  summary?: string
  publishTime?: string
  viewCount?: number
  likeCount?: number
  commentCount?: number
  coverImage?: string
  tags?: string
  categoryName?: string
  status?: number // 添加status字段
}

// 新增热门文章
export async function POST(req: Request) {
  try {
    const articleData: HotArticle = await req.json()
    // 验证必填字段
    if (!articleData.post_id || !articleData.title) {
      return NextResponse.json(
        { code: 400, message: 'post_id和title为必填字段' },
        { status: 400 }
      )
    }
    
    const client = await pool.getConnection()
    
    try {
     // 检查post_id是否已存在
     const checkQuery = 'SELECT COUNT(*) as count FROM wp_hot_posts WHERE id = ?'
     const [checkResult] = await client.query(checkQuery, [articleData.post_id])
     
     // 修复第37行
     interface CheckResult {
       count: number;
     }
     
     if ((checkResult as CheckResult[])[0].count > 0) {
       return NextResponse.json(
         { code: 400, message: '该文章ID已存在或为删除状态，请检查后重试' },
         { status: 400 }
       )
     }
      const query = `
        INSERT INTO wp_hot_posts (
          id, title, summary, publishTime, viewCount, 
          likeCount, commentCount, coverImage, tags, categoryName, status
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      `
      
      const values = [
        articleData.post_id,
        articleData.title,
        articleData.summary || '',
        articleData.publishTime || new Date().toISOString(),
        articleData.viewCount || 0,
        articleData.likeCount || 0,
        articleData.commentCount || 0,
        articleData.coverImage || '',
        // 将数组转换为JSON字符串或逗号分隔的字符串
        articleData.tags || null,
        articleData.categoryName || null,
        1 // 默认status为1（激活状态）
      ]

      await client.query(query, values)
      
      return NextResponse.json(
        { code: 200, message: '添加成功' },
        { status: 200 }
      )
    } finally {
      client.release()
    }
  } catch (error) {
    console.error('添加热门文章失败:', error)
    return NextResponse.json(
      {
        code: 500,
        message: '服务器内部错误',
        error: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    )
  }
}

// 编辑热门文章
export async function PUT(req: Request) {
  try {
    const articleData: HotArticle = await req.json()
    
    // 验证必填字段
    if (!articleData.id || !articleData.title) {
      return NextResponse.json(
        { code: 400, message: 'id和title为必填字段' },
        { status: 400 }
      )
    }
    
    const client = await pool.getConnection()
    
    try {
      const query = `
        UPDATE wp_hot_posts SET 
          title = ?, 
          summary = ?, 
          publishTime = ?, 
          viewCount = ?, 
          likeCount = ?, 
          commentCount = ?, 
          coverImage = ?, 
          tags = ?, 
          categoryName = ?
        WHERE id = ?
      `
      
      const values = [
        articleData.title,
        articleData.summary || '',
        articleData.publishTime || new Date().toISOString(),
        articleData.viewCount || 0,
        articleData.likeCount || 0,
        articleData.commentCount || 0,
        articleData.coverImage || '',
        articleData.tags || '',
        articleData.categoryName || '',
        articleData.id
      ]
      
      const [result] = await client.query(query, values)
      
      if ((result as any).affectedRows === 0) {
        return NextResponse.json(
          { code: 404, message: '文章不存在' },
          { status: 404 }
        )
      }
      
      return NextResponse.json(
        { code: 200, message: '编辑成功' },
        { status: 200 }
      )
    } finally {
      client.release()
    }
  } catch (error) {
    console.error('编辑热门文章失败:', error)
    return NextResponse.json(
      {
        code: 500,
        message: '服务器内部错误',
        error: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    )
  }
}

// 删除热门文章 (修改为软删除)
export async function DELETE(req: Request) {
  try {
    const { id } = await req.json()
    
    if (!id) {
      return NextResponse.json(
        { code: 400, message: 'id为必填字段' },
        { status: 400 }
      )
    }
    
    const client = await pool.getConnection()
    
    try {
      // 修改为软删除，将status字段设置为0
      const query = 'UPDATE wp_hot_posts SET status = 0 WHERE id = ?'
      const [result] = await client.query(query, [id])
      
      // 修复第133行和第178行
      interface QueryResult {
        affectedRows: number;
      }
      
      if ((result as QueryResult).affectedRows === 0) {
        return NextResponse.json(
          { code: 404, message: '文章不存在' },
          { status: 404 }
        );
      }
      
      return NextResponse.json(
        { code: 200, message: '删除成功' },
        { status: 200 }
      )
    } finally {
      client.release()
    }
  } catch (error) {
    console.error('删除热门文章失败:', error)
    return NextResponse.json(
      {
        code: 500,
        message: '服务器内部错误',
        error: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    )
  }
}

// 搜索文章或获取热门文章列表
export async function GET(req: Request) {
  try {
    const { searchParams } = new URL(req.url)
    const keyword = searchParams.get('keyword')
    const id = searchParams.get('id')
    
    // 如果有id参数，则返回文章详情
    if (id) {
      const client = await pool.getConnection()
      
      try {
        const query = 'SELECT * FROM wp_hot_posts WHERE id = ? AND status = 1'
        const [result] = await client.query(query, [id])

        if ((result as any).length === 0) {
          return NextResponse.json(
            { code: 404, message: '文章不存在' },
            { status: 404 }
          )
        }

        return NextResponse.json(
          { code: 200, data: result[0] },
          { status: 200 }
        )
      } finally {
        client.release()
      }
    }
    // 如果有keyword参数，则执行搜索
    else if (keyword) {
      const client = await pool.getConnection()
      
      try {
        const query = `
          SELECT id, post_title as title 
          FROM wp_posts 
          WHERE post_title LIKE ? AND post_status = 'publish'
          LIMIT 20
        `
        
        const [result] = await client.query(query, [`%${keyword}%`])

        return NextResponse.json(
          { code: 200, data: result },
          { status: 200 }
        )
      } finally {
        client.release()
      }
    } 
    // 如果没有keyword参数，则返回热门文章列表
    else {
      const client = await pool.getConnection()
      
      try {
        const query = `
          SELECT * 
          FROM wp_hot_posts 
          WHERE status = 1
          ORDER BY id DESC
        `
        
        const [result] = await client.query(query)

        return NextResponse.json(
          { code: 200, data: result },
          { status: 200 }
        )
      } finally {
        client.release()
      }
    }
  } catch (error) {
    console.error('获取文章失败:', error)
    return NextResponse.json(
      {
        code: 500,
        message: '服务器内部错误',
        error: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    )
  }
}